package idv.cjcat.stardust.common.math;

import org.w3c.dom.Element;

import idv.cjcat.stardust.common.StardustElement;
import idv.cjcat.stardust.common.xml.XMLBuilder;
	
	/**
	 * This class calls a <code>Random</code> object's <code>random()</code> method multiple times, 
	 * and averages the value.
	 * 
	 * <p>
	 * The larger the sample count, the more normally distributed the results.
	 * </p>
	 */
	public class AveragedRandom extends Random {
		
		public Random randomObj;
		public int sampleCount;
		
		public AveragedRandom(Random randomObj, int sampleCount) {
			this.randomObj = randomObj;
			this.sampleCount = sampleCount;
		}
		
		public AveragedRandom(Random randomObj) {
			this.randomObj = randomObj;
			this.sampleCount = 3;
		}
		
		@Override
		public final double random() {
			if (randomObj==null) return 0;
			
			int sum = 0;
			for (int i = 0; i < sampleCount; i++) sum += randomObj.random();
			
			return sum / sampleCount;
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		@Override 
		public StardustElement[] getRelatedObjects() {
			StardustElement[] related = {randomObj};
			return related;
		}
		
		@Override
		public String getXMLTagName() {
			return "AveragedRandom";
		}
		
		@Override
		public Element toXML() {
			Element xml = super.toXML();
			
			xml.setAttribute("randomObj", randomObj.name);
			xml.setAttribute("sampleCount", "" + sampleCount);
			
			return xml;
		}
		
		@Override
		public void parseXML(Element xml, XMLBuilder builder) {
			super.parseXML(xml, builder);
			
			if (xml.hasAttribute("randomObj")) randomObj = (Random) builder.getElementByName(xml.getAttribute("randomObj"));
			try {
				if (xml.hasAttribute("sampleCount")) sampleCount = Integer.parseInt(xml.getAttribute("sampleCount"));
			}catch (NumberFormatException e) {
	            e.printStackTrace();
	        } 
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
